import React from 'react';
import copy from 'copy-to-clipboard';
import { connect } from 'dva';
import {
  Tabs,
  WhiteSpace,
  List,
  Button,
  Icon,
  Popup,
  Tag,
  Toast,
  Popover,
  Modal,
} from 'antd-mobile';
import Container from '../components/Base/Container';
import VipListShow from '../components/Base/VipInfoShow';
import VipShopShow from '../components/Base/VipShopShow';
import VipInfoRemarksPage from './VipInfoRemarksPage';
import VisitFunction from '../components/Base/VisitFunction';
import VisitedRecord from '../components/Base/VisitedRecord';
import { CouponList, CouponCodeList } from '../components/Base/CouponCode';
import { routerRedux } from 'dva/router';
import config from '../utils/config';
import styles from './PrecisionPage1_info.css';
import * as taskService from "../services/taskService";
import moment from "moment";


const Item = List.Item;
const TabPane = Tabs.TabPane;
const alert = Modal.alert;


const s = n => {
  return styles[n];
};


const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let maskProps;
if (isIPhone) {
  // Note: the popup content will not scroll.
  maskProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

class PrecisionPage1Info extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    value: 0,
    value2: 0,
    value3: 0,
    value4: 0,
    visible: false,
    clicked: 'none',
    clicked1: 'none',
    clicked2: 'none',
    copyText: '',
    showMore: false,
    showAlert: false,
    waitList: [],
    item: {
      updateAt: new moment(),
      type: -1,
    },
  };

  onCopy = (e) => {
    const text = e.target.parentElement.parentElement.getElementsByTagName('p')[0].innerText;
    if (text) {
      this.setState({ copyText: text });
      setTimeout(() => {
        copy(text);
      }, 50);
    }
  };
  onCopy2 = (e) => {
    if (this.state.copyText) {
      const u = navigator.userAgent;
      if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
        e.clipboardData.setData('text/plain', this.state.copyText);
        e.preventDefault();
      }
      Toast.info('复制成功', 1);
      this.setState({ copyText: '' });
    }
  };
  replaceVipInfo = (text) => {
    const { consume_items } = this.props.vipInfo;
    let i = 0;
    if (this.props.location.query.taskType !== '5') {
      text = '您好！我是[]店铺的客户专员[]。您上次在我们店买的[],宝宝用得怎么样啦？';
    }
    const { branchName, saleManName } = this.props.currentUser;
    const v = [null, branchName, saleManName, consume_items ? consume_items.join(',') : ''];
    return text.replace(/（系统自动调取）/ig, '').replace(/(\[\])/ig, (a, b, c) => {
      i += 1;
      return `【${v[i]}】`;
    });
  };

  onClick1 = (item) => {
    Popup.show(<div>
      <List
        renderHeader={item => (
          <div style={{ position: 'relative' }}>
              话术
              <span
                style={{
                  position: 'absolute', right: 3, top: -5,
                }}
                onClick={() => this.onClose('cancel')}
              >
                <Icon type="cross" />
              </span>
          </div>)}
      >
        <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
          {item.closerRelation && <List.Item wrap>
            <Tag selected>拉近关系</Tag>
            <Button style={{ float: 'right' }} size="small" onClick={e => this.onCopy(e)}>复制</Button>
            <p>{this.replaceVipInfo(item.closerRelation)}</p>
          </List.Item>}
          {item.parentingKnowledge && <List.Item wrap>
            <Tag selected>育儿知识</Tag>
            <Button style={{ float: 'right' }} size="small" onClick={e => this.onCopy(e)}>复制</Button>
            <p> {item.parentingKnowledge}</p>
          </List.Item>}
          {item.recommendTalk && <List.Item wrap>
            <Tag selected>产品推荐</Tag>
            <Button style={{ float: 'right' }} size="small" onClick={e => this.onCopy(e)}>复制</Button>
            <p>{item.recommendTalk}</p>
          </List.Item>}
          {item.closeTalk && <List.Item wrap>
            <Tag selected>结束语</Tag>
            <Button style={{ float: 'right' }} size="small" onClick={e => this.onCopy(e)}>复制</Button>
            <p>{item.closeTalk}</p>
          </List.Item>}
        </div>

      </List>
    </div>,
      { animationType: 'slide-up', maskProps, maskClosable: false });
  };

  componentDidMount() {
    this.props.fetchVisitedRecord();
    this.props.fetchVipInfo();
    this.props.fetchVipConsume();
    this.props.fetchVipRecommend();

    const { currentUser, cardNo } = this.props;
    // this.props.fetchVipAcc(currentUser.shopId,cardNo);

    document.addEventListener('copy', this.onCopy2);
    const {cardId, check} = this.props.location.query;

    console.log("currentUser", currentUser);
    console.log("测试法大师傅", this.props.sss);

    if (this.props.sss && _.isString(check) && check === "1" && _.isString(currentUser.salemanId) && currentUser.salemanId.length > 0) {
      taskService.myVisitTasks(currentUser.shopId, currentUser.branchNo, cardNo, 1).then(res => {
        const {completeList, waitList} = res.data;

        if (_.isArray(completeList) && completeList.length > 0) {
          // this.showAlert(completeList[0], waitList);

          this.setState({
            item: completeList[0],
            waitList,
            showAlert: true});
        } else {
          if (waitList.length > 1) {
            this.handleMulti();
          }
        }
      });
    }
  }

  showAlert = (item, waitList) => {
    const alertInstance = alert(
      <div className={s('valert')}><img src={require('../assets/v3.0/warning.png')} alt="warning"/><h3>该会员7天内已进行过回访</h3></div>,
      <div className={s('vbody')}>
        <p>上次回访时间：{moment(item.updateAt).utc(true).format("MM-DD HH:mm:ss")}</p>
        <p>上次回访任务：{this.getTaskType(item.type)}</p>
      </div>,
      [
        {text: '继续回访', onPress: () => { if (waitList.length > 1) {this.handleMulti()}  return 0}},
        {text: '取消任务', onPress: () => { this.cancelTask(); return 0}},
        {text: '不操作', onPress: () => console.log('ok')},
      ]);
  };

  handleMulti = () => {
    // const search = queryString.parse(this.props.location.search);
    const { cardId, cardNo} = this.props.location.query;
    // const  = search.cardNo;
    this.props.gotoMultiTask(cardId, cardNo);
  };

  cancelTask = () => {
    const { cardId, cardNo} = this.props.location.query;
    const {currentUser} = this.props;
    taskService.cancelTask(currentUser.shopId, currentUser.branchNo, cardNo, currentUser.salemanId);
  };

  componentWillUnmount() {
    document.removeEventListener("copy", this.onCopy2);
    this.onClose('cancel');
  }

  onChange = (key) => {
    if (key === 1) {
    } else if (key === '2') {
    } else if (key === '4') {
      this.props.fetchVipCouponCodes();
    } else if (key === '5') {
      this.props.fetchShopCoupons();
    }
  };
  onClose = (sel) => {
    Popup.hide();
  };

  sendWX = (boolean) => {
    this.setState({
      visible: boolean,
    });
  };

  onRemarksClick = () => {
    const { saveRemarks, vipInfo } = this.props;
    Popup.show(<VipInfoRemarksPage
      onSave={(text) => {
        saveRemarks(vipInfo._id, text);
        Popup.hide();
      }}
      value={vipInfo.remarks}
    />,
      { animationType: 'slide-up', maskClosable: false });
  };
  getTaskType = type => {
    switch (type) {
      case 0:
        return "新客转化";
      case 3:
        return "沉睡唤醒";
      case 4:
        return "流失挽回";
      case 8:
        return "新客回头";
      case 9:
        return "新客转惯";
      case 15:
        return "老客关怀";
      case 16:
        return "入会关怀";
      case 5:
        return "成长关怀";
      case 6:
        return "升阶升码";
      case 7:
        return "纸尿裤升码";
      case 101:
        return "自定义回访";
      case 12:
        return "疫苗提醒";
      case 13:
        return "奶粉提醒";
      case 14:
        return "纸尿裤提醒";
      case 11:
        return "积分提醒";
      case 10:
        return "老客复购";
    }

    console.log("未匹配的：", type);
    return "";
  };

  getTitle = () => {
    return this.props.location.query.title;
  };

  hideShare = () => {
    this.setState({
      visible: false,
    });
  };

  closeAlert = () => {
    this.setState({
      showAlert: false,
    });
  };

  render() {
    console.log("this.state.showAlert", this.state.showAlert);
    const { vipInfo, vipConsume, currentUser, vipInfoAcc, recommend } = this.props;
    const { taskType, subType } = this.props.location.query;
    let recommendList = [];
    if (taskType == '5' ) {
      recommendList.push({
        _id: Math.random(),
        goodsRecommend: '非商品类',
        closerRelation: config.talk[subType],
      });
    }
    recommendList = _.concat(recommendList, recommend);
    return (
      <Container
        title={this.getTitle()} navOption={{
          rightContent: <Popover
            mask
            transitionName="fade"
            overlayClassName="fortest"
            overlayStyle={{ color: 'currentColor' }}
            visible={false}
            overlay={[
            (<Item key="4" value="scan">点击右上角，分享给朋友</Item>),
            ]}
            align={{
              offset: [-200, -200],
              targetOffset: ['30%', '40%'],
            }}
            onVisibleChange={(e) => {
              this.sendWX(e);
            }}
            onSelect={this.onSelect}
          >
            <span />
          </Popover>,
        }}
      >
      {this.state.visible &&
        <div className={styles["shareFunction"]} onClick={this.hideShare}>
          <span className={styles["sftt"]}>点击右上角，分享给朋友</span>
        </div>
      }

       <Modal
          title={ <div className={s('valert')}><img src={require('../assets/v3.0/warning.png')} alt="warning"/><h3>该会员7天内已进行过回访</h3></div>}
          transparent
          maskClosable={false}
          visible={this.state.showAlert}
          onClose={this.closeAlert}
          footer={
            [
              {text: '继续回访', onPress: () => { if (this.state.waitList.length > 1) {this.handleMulti()} this.closeAlert(); return 0}},
              {text: '取消任务', onPress: () => { this.cancelTask(); this.closeAlert(); return 0;}},
              {text: '不操作', onPress: () => this.closeAlert()},
            ]
          }
          platform="ios"
        >
         <div className={s('vbody')}>
           <p>上次回访时间：{moment(this.state.item.updateAt).format("MM-DD HH:mm:ss")}</p>
           <p>上次回访任务：{this.getTaskType(this.state.item.type)}</p>
         </div>
        </Modal>

        <VipListShow
          rowData={vipInfo}
          vipInfoAcc={_.get(vipInfo, 'now_acc_num', 0)}
          onRemarksClick={this.onRemarksClick}
          onLabelClick={this.props.onLabelClick}
        />

        <Tabs defaultActiveKey="2" onChange={this.onChange} swipeable={false} pageSize={5}>
          <TabPane tab="回访记录" key="1">
            <VisitedRecord />
          </TabPane>
          <TabPane tab="消费记录" key="2">
            <VipShopShow vipConsume={vipConsume} />
          </TabPane>
          <TabPane tab="商品推荐" key="3">
            <div>
              <List renderHeader={() => `共 ${this.props.recommend.length} 条`}>
                {recommendList.map((item, index) => {
                  if (index < 3 || this.state.showMore) {
                    return (
                      <Item
                        key={item._id || item.goodsRecommend}
                        extra={<Button
                          onClick={() => {
                            this.onClick1(item);
                          }
                          } size="small" inline
                        >话术</Button>}
                      >
                        {item.goodsRecommend} <span
                          style={{ color: '#888888', fontSize: '12px' }}
                        >({item.goodsSpec})</span>
                      </Item>
                    );
                  }
                })}
                {
                  !this.state.showMore &&
                  <Item
                    onClick={() => {
                      this.setState({ showMore: true });
                    }}
                  >
                    <div style={{ textAlign: "center" }}>显示更多</div>
                  </Item>
                }
              </List>
            </div>
          </TabPane>
          <TabPane tab="优惠券" key="4">
            <CouponCodeList couponList={this.props.couponList} couponCodeList={this.props.couponCodeList} />
          </TabPane>
          <TabPane tab="我要发券" key="5">
            <CouponList
              taskType={taskType}
              user={this.props.currentUser}
              onSend={this.props.sendCoupon}
              couponList={this.props.couponList}
              couponCodeList={this.props.couponCodeList}
            />
          </TabPane>
        </Tabs>
        <WhiteSpace />
        {/* {this.renderActionBar()}*/}
        <VisitFunction
          sendWX={this.sendWX}
          location={this.props.location}
        />
      </Container>
    );
  }
}

export default connect((state, props) => {
  return {
    couponList: state.coupon.couponList,
    couponCodeList: state.coupon.codeList,
    currentUser: state.auth.currentUser,
    cardNo: props.location.query.cardNo,
    vipInfo: state.task.vipInfo,
    vipInfoAcc: state.task.vipInfoAcc,
    vipConsume: state.task.vipConsume,
    recommend: state.task.recommend,
    sss: state.task.sss,
  };
}, (dispatch, props) => {
  return {
    fetchVisitedRecord() {
      const cardNo = props.location.query.cardNo;
      dispatch({
        type: 'task/fetchVisitedRecord',
        payload: { cardNo },
      });
    },
    fetchVipInfo() {
      const card_id = props.location.query.cardId;
      dispatch({
        type: 'task/fetchVipInfo',
        payload: { card_id },
      });
    },
    fetchVipConsume() {
      const card_id = props.location.query.cardId || props.location.query.cardId;
      dispatch({
        type: 'task/fetchVipConsume',
        payload: { card_id },
      });
    },
    fetchVipRecommend() {
      const { taskType, subType, cardNo: card_no } = props.location.query;
      dispatch({
        type: 'task/fetchRecommend',
        payload: { taskType, subType, card_no },
      });
    },
    saveRemarks(_id, remarks) {
      const { cardNo } = props.location.query;
      dispatch({
        type: 'vip/updateRemarks',
        payload: { _id, cardNo, remarks },
      });
    },
    fetchVipAcc(shopId, cardNo) {
      dispatch({
        type: 'task/fetchVipAcc',
        payload: { shopId, cardNo },
      });
    },
    fetchVipCouponCodes() {
      const cardNo = props.location.query.cardId || props.location.query.cardNo;
      dispatch({
        type: 'coupon/fetchVipCouponCodes',
        payload: { card_id: cardNo },
      });
    },
    fetchShopCoupons() {
      dispatch({
        type: 'coupon/fetchShopCoupons',
        payload: {},
      });
    },
    sendCoupon(coupon) {
      const cardNo = props.location.query.cardId || props.location.query.cardNo;
      dispatch({
        type: 'coupon/sendCoupon',
        payload: { coupon, card_id: cardNo },
      });
    },
    onLabelClick() {
      const { taskType, subType } = props.location.query;
      dispatch(routerRedux.push({
        pathname: '/labelEdit',
        query: {
          cardNo: props.location.query.cardNo,
          cardId: props.location.query.cardId,
          taskType,
          subType,
        },
      }));
    },
    gotoMultiTask(cardId, cardNo) {
      dispatch(routerRedux.push({
        pathname: `/multiTask`,
        query: {
          cardId: cardId,
          cardNo: cardNo,
        },
      }));
    }
  };
  })(PrecisionPage1Info);
